package com.example.supplychainbackend.controller;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import org.hyperledger.fabric.client.*;
import org.hyperledger.fabric.protos.common.Envelope;
import org.hyperledger.fabric.protos.common.Payload;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;

@RestController
@AllArgsConstructor
public class HelloController {
//    final Gateway gateway1;
//    final Contract contract1;
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();

    @GetMapping("/hello")
    public String hello() {
        return "Hello, supply chain!";
    }

//    @GetMapping("/fabric")
//    public String fabric() throws GatewayException, CommitException, InvalidProtocolBufferException {
//        Proposal proposal = contract1.newProposal("CreateForm")
//                .addArguments("key4", "2333333")
//                .build();
//        Transaction transaction = proposal.endorse();
//        SubmittedTransaction comm = transaction.submitAsync();  // 返回 Transaction 对象
//
//
//        // 立即获取交易ID（无论最终是否成功）
//        String transactionId = transaction.getTransactionId();
//        System.out.println("Transaction ID: " + transactionId);
//
//        // 等待并获取提交状态
//        Status commitStatus = comm.getStatus();
//        long blockNumber = commitStatus.getBlockNumber();
//        boolean isValid = commitStatus.isSuccessful();
//
//        System.out.println("区块: " + blockNumber + ", id: " + transactionId + ", 有效: " + isValid);
//
////        contract1.submitTransaction("CreateForm","key1","2333333");
////        byte[] result = contract1.evaluateTransaction("ReadForm", "key1");
//
//        return "*** Result:" + prettyJson(transactionId);
//    }

    private String prettyJson(final byte[] json) {
        return prettyJson(new String(json, StandardCharsets.UTF_8));
    }

    private String prettyJson(final String json) {
        var parsedJson = JsonParser.parseString(json);
        return gson.toJson(parsedJson);
    }

    private static String calculateSHA256Hex(byte[] data) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(data);
            return bytesToHex(hash);
        } catch (Exception e) {
            throw new RuntimeException("SHA-256计算失败", e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}